package com.hjm.project.channel.agent.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hjm.common.api.ls.leshua.LeShuaUtil;
import com.hjm.common.api.ls.leshua.entity.TermDto;
import com.hjm.common.api.ls.leshua.ls.ImageUtil;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.file.FileUploadUtils;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.text.Convert;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.framework.config.BlueConfig;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.framework.web.page.TableDataInfo;
import com.hjm.project.accounts.accounts.domain.Accounts;
import com.hjm.project.accounts.accounts.service.IAccountsService;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.service.IAgentInfoService;
import com.hjm.project.agentInfo.agentInfo.utils.Utils;
import com.hjm.project.channel.agent.domain.ChannelAgent;
import com.hjm.project.channel.agent.domain.Fee;
import com.hjm.project.channel.agent.domain.FeeListRequest;
import com.hjm.project.channel.agent.domain.request.*;
import com.hjm.project.channel.agent.service.IChannelAgentService;
import com.hjm.project.channel.picturesInfo.domain.AgentPicturesInfo;
import com.hjm.project.channel.picturesInfo.service.IAgentPicturesInfoService;
import com.hjm.strategy.AgentStrategy;
import com.hjm.strategy.AgentStrategyContext;
import com.yxhd.encrypt.EncryptUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 渠道代理商Controller
 *
 * @author maker-platform
 * @date 2025-05-21
 */
@Controller
@RequestMapping("/channel/agent")
public class ChannelAgentController extends BaseController {
    private String prefix = "channel/agent";

    @Resource
    private IChannelAgentService channelAgentService;
    @Resource
    private IAgentPicturesInfoService agentPicturesInfoService;

    @Resource
    private IAgentInfoService agentInfoService;
    @Resource
    private IAccountsService accountsService;
    @Autowired
    private AgentStrategyContext strategyContext;

    @RequiresPermissions("channel:agent:view")
    @GetMapping()
    public String agent() {
        return prefix + "/agent";
    }

    /**
     * 查询渠道代理商列表
     */
    @RequiresPermissions("channel:agent:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ChannelAgent channelAgent) {
        startPage();
        List<ChannelAgent> list = channelAgentService.selectChannelAgentList(channelAgent);
        // 遍历每个对象，解析 baseInfo 字段
        for (ChannelAgent agent : list) {
            String baseInfoJson = agent.getBaseInfo();
            if (baseInfoJson != null && !baseInfoJson.isEmpty()) {
                try {
                    JSONObject baseInfoObj = JSON.parseObject(baseInfoJson);
                    // 提取字段并赋值
                    agent.setEnterpriseTitle(baseInfoObj.getString("enterpriseTitle"));
                    agent.setLegalPersonName(baseInfoObj.getString("legalPersonName"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出渠道代理商列表
     */
    @RequiresPermissions("channel:agent:export")
    @Log(title = "渠道代理商", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ChannelAgent channelAgent) {
        List<ChannelAgent> list = channelAgentService.selectChannelAgentList(channelAgent);
        ExcelUtil<ChannelAgent> util = new ExcelUtil<ChannelAgent>(ChannelAgent.class);
        return util.exportExcel(list, "agent");
    }

    /**
     * 新增渠道代理商
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    @GetMapping("/addRate/{agentId}")
    public String addRate(@PathVariable("agentId") String agentId, ModelMap mmap) {
        ChannelAgent channelAgent = channelAgentService.selectChannelAgentByAgentId(agentId);
        if (StringUtils.isEmpty(channelAgent.getCAgentId())) {
            throw new BusinessException("代理信息异常");
        }
        mmap.put("targetAgentId", channelAgent.getAgentId());
        if (channelAgent.getFeeInfo() != null) {
            List<Fee> feeList = JSON.parseObject(channelAgent.getFeeInfo(), new TypeReference<List<Fee>>() {
            });
            mmap.addAttribute("feeList", feeList);
        }
        return prefix + "/addRate";
    }

    @GetMapping("/queryAgentInfo")
    public String queryAgentInfo() {
        return prefix + "/queryAgentInfo";
    }

    @PostMapping("/queryAgentInfoList")
    @ResponseBody
    public TableDataInfo queryAgentInfoList(ChannelAgent channelAgent) throws Exception {
        startPage();
        List<ChannelAgent> list = channelAgentService.selectChannelAgentList(channelAgent);
        // 遍历每个对象，解析 baseInfo 字段
        for (ChannelAgent agent : list) {
            String baseInfoJson = agent.getBaseInfo();
            if (baseInfoJson != null && !baseInfoJson.isEmpty()) {
                try {
                    JSONObject baseInfoObj = JSON.parseObject(baseInfoJson);
                    // 提取字段并赋值
                    agent.setEnterpriseTitle(baseInfoObj.getString("enterpriseTitle"));
                    agent.setLegalPersonName(baseInfoObj.getString("legalPersonName"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return getDataTable(list);
    }

    @GetMapping("/queryRate/{agentId}")
    public String queryRate(@PathVariable("agentId") String agentId, ModelMap mmap) {
        ChannelAgent channelAgent = channelAgentService.selectChannelAgentByAgentId(agentId);
        FeeListRequest feeListRequest = new FeeListRequest();
        feeListRequest.setTargetAgentId(channelAgent.getCAgentId());
        feeListRequest.setSource(CustomConfig.getSource());
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(feeListRequest, CustomConfig.getBaseUrl() + "/agentInfo/queryAgentCost", CustomConfig.getSignKey());
        if (!baseResult.get("resultCode").toString().equals("0000")) {
            if (channelAgent.getFeeInfo() != null) {
                List<Fee> feeList = JSON.parseObject(channelAgent.getFeeInfo(), new TypeReference<List<Fee>>() {
                });
                mmap.addAttribute("feeList", feeList);
            }
        } else {
            List<Fee> feeList = JSON.parseObject(baseResult.get("data").toString(), new TypeReference<List<Fee>>() {
            });
            mmap.addAttribute("feeList", feeList);
        }
        return prefix + "/queryRate";
    }

    /**
     * 新增保存渠道代理商
     */
    @RequiresPermissions("channel:agent:add")
    @Log(title = "渠道代理商成本", businessType = BusinessType.INSERT)
    @PostMapping("/addRate")
    @ResponseBody
    public AjaxResult addRate(@ModelAttribute FeeListRequest feeListRequest) {
        ChannelAgent channelAgent = channelAgentService.selectChannelAgentByAgentId(feeListRequest.getTargetAgentId());
        if (channelAgent == null) {
            return AjaxResult.error("代理商不存在");
        }
        feeListRequest.setTargetAgentId(channelAgent.getCAgentId());
        feeListRequest.setSource(CustomConfig.getSource());
        if (StringUtils.isEmpty(channelAgent.getFeeInfo())) {
            Map<String, Object> baseResult = LeShuaUtil.commonRemote(feeListRequest, CustomConfig.getBaseUrl() + "/agentInfo/addAgentCost", CustomConfig.getSignKey());
            if (baseResult.get("resultCode").toString().equals("0000")) {
                channelAgent.setStatus("0");
                channelAgent.setFeeInfo(JSONObject.toJSONString(feeListRequest.getFeeList()));
            } else {
                return AjaxResult.error(baseResult.get("resultMsg").toString());
            }
        } else {
            Map<String, Object> baseResult = LeShuaUtil.commonRemote(feeListRequest, CustomConfig.getBaseUrl() + "/agentInfo/updateAgentCost", CustomConfig.getSignKey());
            if (baseResult.get("resultCode").toString().equals("0000")) {
                channelAgent.setFeeInfo(JSONObject.toJSONString(feeListRequest.getFeeList()));
            } else {
                return AjaxResult.error(baseResult.get("resultMsg").toString());
            }
        }

        return toAjax(channelAgentService.updateChannelAgent(channelAgent));
    }

    /**
     * 新增保存渠道代理商
     */
    @RequiresPermissions("channel:agent:add")
    @Log(title = "渠道代理商", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ChannelAgent channelAgent, @RequestParam("imageFiles") List<MultipartFile> imageFiles, @RequestParam("imageTypes") List<String> imageTypes) throws Exception {
        if (imageFiles.size() != imageTypes.size()) {
            return AjaxResult.error("上传的图片和类型数量不匹配");
        }
        ChannelAgent queryAgent = channelAgentService.selectChannelAgentByAgentId(channelAgent.getAgentId());
        if (queryAgent != null) {
            return AjaxResult.error("代理已存在");
        }
        AgentStrategy strategy = strategyContext.getStrategy(channelAgent.getChannelCode());
        AgentPicturesInfo picturesInfo = new AgentPicturesInfo();
        ChannelPicturesInfo channelPicturesInfo = new ChannelPicturesInfo();
        picturesInfo.setAgentId(channelAgent.getAgentId());
        // 逐个处理图片和类型
        for (int i = 0; i < imageFiles.size(); i++) {
            MultipartFile file = imageFiles.get(i);
            String type = imageTypes.get(i);
            String path = uploadFileByStrategy(file);
            // tring path = uploadImg(file);
//            String channelPath = saveFile(path);
            String channelPath = strategy.uploadFile(path);
            // 这里写保存逻辑，比如存文件、数据库等
            if (type.equals("idCardFrontPic")) {
                picturesInfo.setIdCardFrontPic(path);
                channelPicturesInfo.setIdCardFrontPic(channelPath);
            } else if (type.equals("idCardBackPic")) {
                picturesInfo.setIdCardBackPic(path);
                channelPicturesInfo.setIdCardBackPic(channelPath);
            } else if (type.equals("businessLicensePic")) {
                picturesInfo.setBusinessLicensePic(path);
                channelPicturesInfo.setBusinessLicensePic(channelPath);
            } else if (type.equals("publicAccountPic")) {
                picturesInfo.setPublicAccountPic(path);
                channelPicturesInfo.setPublicAccountPic(channelPath);
            } else if (type.equals("settleBankCardFrontPic")) {
                picturesInfo.setSettleBankCardFrontPic(path);
                channelPicturesInfo.setSettleBankCardFrontPic(channelPath);
            }
        }
        agentPicturesInfoService.insertAgentPicturesInfo(picturesInfo);
        channelAgent.setPicturesInfo(JSON.toJSONString(channelPicturesInfo));
        AgentInfo agentInfo = agentInfoService.selectAgentInfoByAgentNum(channelAgent.getAgentId());
        Accounts acc = new Accounts();
        acc.setSeqId(channelAgent.getAgentId());
        Accounts accounts = accountsService.selectAccounts(acc);

        //代理商联系人信息
        ChannelContactInfo contactInfo = new ChannelContactInfo();
        contactInfo.setAgentAccount(agentInfo.getAgentNum());
        contactInfo.setContactEmail(agentInfo.getLinkEmail());
        contactInfo.setContactMobile(agentInfo.getLinkPhone());
        channelAgent.setContactInfo(JSON.toJSONString(contactInfo));

        //基础信息
        ChannelBaseInfo channelBaseInfo = new ChannelBaseInfo();
//        channelBaseInfo.setAgentLevel(""); //代理商等级；一代必须指定为1，子代不需要填
        channelBaseInfo.setAgentParentId(CustomConfig.getSubAgentId());//一级代理
        //账户类型 （1：对公  2：对私 ）===代理商性质：0：企业1：个人2：个体工商户
        channelBaseInfo.setAgentProperty(accounts.getNature() == 1 ? "0" : "1");
//        channelBaseInfo.setAgentQualification("");//代理商可不填
        channelBaseInfo.setAddBd("test");
        channelBaseInfo.setAgentAddress(agentInfo.getAgentArea());
        //非个体必填
        if (!StringUtils.equals(channelBaseInfo.getAgentProperty(), "1")) {
            channelBaseInfo.setEnterpriseTitle(agentInfo.getAgentName());
            channelBaseInfo.setCreditCode(agentInfo.getOrganCode());
            channelBaseInfo.setBusinessLicenseEndDate(channelAgent.getBusinessLicenseEndDate());//营业执照有效期
        }
        // 交由策略处理新增逻辑前，补充 KDB 渠道证件有效期逻辑
        if ("KDB".equalsIgnoreCase(channelAgent.getChannelCode())) {
            // 如果是 KDB 渠道
            channelAgent.setLegalPersonCertEndDate(channelAgent.getLegalPersonCertPeriod()); //  20220214-20320214 替换一下
        }
        channelBaseInfo.setLegalPersonName(agentInfo.getCommissary());
        channelBaseInfo.setLegalPersonCertEndDate(channelAgent.getLegalPersonCertEndDate());//法人有效证件有效期 ---暂无
        channelBaseInfo.setLegalPersonMobile(agentInfo.getLinkPhone());
        if (agentInfo.getIdentityNum() != null) {
            channelBaseInfo.setLegalPersonIdCard(EncryptUtils.getDecrypt(agentInfo.getIdentityNum()));
        }
        //账户的区域
        String areaNames = agentInfo.getAreaName();
        if (StringUtils.isNotEmpty(areaNames)) {
            String[] splitAreaName = areaNames.split(",");
            channelBaseInfo.setAgentProvince(splitAreaName[0]);
            channelBaseInfo.setAgentCity(splitAreaName[1]);
            channelBaseInfo.setProvince(splitAreaName.length == 3 ? splitAreaName[2] : "");
        }
        channelAgent.setBaseInfo(JSON.toJSONString(channelBaseInfo));

        ChannelSettleInfo settleInfo = new ChannelSettleInfo();
        //账户类型 （1：对公  2：对私 ）===渠道账号类型: 1=对私, 2=对公
        settleInfo.setBankAccountType(accounts.getNature() == 1 ? "2" : "1");
        //结算方式 legalPerson -法人结算，company -对公结算
        settleInfo.setSettObType(accounts.getNature() == 1 ? "company" : "legalPerson");
        settleInfo.setBankAccountNo(EncryptUtils.getDecrypt(accounts.getScreenNum()));
        settleInfo.setBankCardHolder(accounts.getScreenName());
        settleInfo.setBankMobile(EncryptUtils.getDecrypt(accounts.getResphone()));
        settleInfo.setBankUnionpayCode(accounts.getBankNum());
        settleInfo.setBankId(channelAgent.getBankId());
        channelAgent.setSettleInfo(JSON.toJSONString(settleInfo));


        ChannelBusinessInfo channelBusinessInfo = new ChannelBusinessInfo();
        channelBusinessInfo.setDrawPattern(channelAgent.getDrawPattern());//分润提取模式:1=按天,2=按月 暂无
        channelBusinessInfo.setProfitRuleType(channelAgent.getProfitRuleType());
        channelBusinessInfo.setLowerDivideCent(channelAgent.getLowerDivideCent());
        channelBusinessInfo.setSubProfitBillFlag(channelAgent.getSubProfitBillFlag());
        channelAgent.setBusinessInfo(JSON.toJSONString(channelBusinessInfo));

        AgentRequest agentRequest = new AgentRequest();
        agentRequest.setAgentId(CustomConfig.getSubAgentId());
        agentRequest.setSource(CustomConfig.getSource());
//        agentRequest.setSubAgentId(channelAgent.getAgentId()); //修改必填
        agentRequest.setModifyUser("ls");
        agentRequest.setContactInfo(contactInfo);
        agentRequest.setBaseInfo(channelBaseInfo);
        agentRequest.setSettleInfo(settleInfo);
        agentRequest.setPicturesInfo(channelPicturesInfo);
        agentRequest.setBusinessInfo(channelBusinessInfo);
//        Map<String, Object> baseResult = LeShuaUtil.commonRemote(agentRequest, CustomConfig.getBaseUrl() + "/agentInfo/subAgent", CustomConfig.getSignKey());
//        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
//            channelAgent.setStatus("1");
//            Map<String, Object>  respData = (Map<String, Object>) baseResult.get("respData");
//            channelAgent.setCAgentId(respData.get("agentId").toString());
//        }else{
//            channelAgent.setStatus("-1");
//        }
//        channelAgent.setChannelResponse(JSON.toJSONString(baseResult));
        // 交由策略处理新增逻辑
        strategy.addAgent(channelAgent, agentRequest);
        return toAjax(channelAgentService.insertChannelAgent(channelAgent));
    }

    /**
     * 修改渠道代理商
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        ChannelAgent channelAgent = channelAgentService.selectChannelAgentById(id);
        AgentPicturesInfo agentPicturesInfo = new AgentPicturesInfo();
        agentPicturesInfo.setAgentId(channelAgent.getAgentId());
        agentPicturesInfo = agentPicturesInfoService.selectAgentPicturesInfoOne(agentPicturesInfo);
        if (agentPicturesInfo != null) {
            agentPicturesInfo.setIdCardFrontPic(CustomConfig.getImgUrl() + agentPicturesInfo.getIdCardFrontPic());
            agentPicturesInfo.setIdCardBackPic(CustomConfig.getImgUrl() + agentPicturesInfo.getIdCardBackPic());
            agentPicturesInfo.setBusinessLicensePic(CustomConfig.getImgUrl() + agentPicturesInfo.getBusinessLicensePic());
            agentPicturesInfo.setSettleBankCardFrontPic(CustomConfig.getImgUrl() + agentPicturesInfo.getSettleBankCardFrontPic());
            channelAgent.setAgentPicturesInfo(agentPicturesInfo);
            mmap.put("agentPicturesInfo", agentPicturesInfo);
        }
        mmap.put("channelAgent", channelAgent);
        return prefix + "/edit";
    }

    /**
     * 修改保存渠道代理商
     */
    @RequiresPermissions("channel:agent:edit")
    @Log(title = "渠道代理商", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ChannelAgent channelAgent, @RequestParam(value = "idCardFrontPic", required = false) MultipartFile idCardFrontPic, @RequestParam(value = "idCardBackPic", required = false) MultipartFile idCardBackPic, @RequestParam(value = "settleBankCardFrontPic", required = false) MultipartFile settleBankCardFrontPic, @RequestParam(value = "businessLicensePic", required = false) MultipartFile businessLicensePic, @RequestParam(value = "publicAccountPic", required = false) MultipartFile publicAccountPic) throws IOException {
        AgentStrategy strategy = strategyContext.getStrategy(channelAgent.getChannelCode());
        if ((idCardFrontPic != null && !idCardFrontPic.isEmpty()) || (idCardBackPic != null && !idCardBackPic.isEmpty()) || (settleBankCardFrontPic != null && !settleBankCardFrontPic.isEmpty()) || (businessLicensePic != null && !businessLicensePic.isEmpty()) || (publicAccountPic != null && !publicAccountPic.isEmpty())) {
            AgentPicturesInfo agentPicturesInfo = new AgentPicturesInfo();
            ChannelPicturesInfo channelPicturesInfo = JSONObject.parseObject(channelAgent.getPicturesInfo(), ChannelPicturesInfo.class);
            agentPicturesInfo.setAgentId(channelAgent.getAgentId());
            agentPicturesInfo = agentPicturesInfoService.selectAgentPicturesInfoOne(agentPicturesInfo);
            if (idCardFrontPic != null && !idCardFrontPic.isEmpty()) {
                String path = uploadFileByStrategy(idCardFrontPic);
                agentPicturesInfo.setIdCardFrontPic(path);
                channelPicturesInfo.setIdCardBackPic(strategy.uploadFile(path));
            }
            if (idCardBackPic != null && !idCardBackPic.isEmpty()) {
                String path = uploadFileByStrategy(idCardBackPic);
                agentPicturesInfo.setIdCardBackPic(path);
                channelPicturesInfo.setIdCardBackPic(strategy.uploadFile(path));
            }
            if (settleBankCardFrontPic != null && !settleBankCardFrontPic.isEmpty()) {
                String path = uploadFileByStrategy(settleBankCardFrontPic);
                agentPicturesInfo.setSettleIdCardBackPic(path);
                channelPicturesInfo.setSettleIdCardBackPic(strategy.uploadFile(path));
            }
            if (businessLicensePic != null && !businessLicensePic.isEmpty()) {
                String path = uploadFileByStrategy(businessLicensePic);
                agentPicturesInfo.setBusinessLicensePic(path);
                channelPicturesInfo.setBusinessLicensePic(strategy.uploadFile(path));
            }
            if (publicAccountPic != null && !publicAccountPic.isEmpty()) {
                String path = uploadFileByStrategy(publicAccountPic);
                agentPicturesInfo.setPublicAccountPic(path);
                channelPicturesInfo.setPublicAccountPic(strategy.uploadFile(path));
            }
            channelAgent.setPicturesInfo(JSON.toJSONString(channelPicturesInfo));
            agentPicturesInfoService.updateAgentPicturesInfo(agentPicturesInfo);
        }
        AgentRequest agentRequest = new AgentRequest();
        agentRequest.setAgentId(CustomConfig.getSubAgentId());
        agentRequest.setSource(CustomConfig.getSource());
        if (!StringUtils.equals("-1", channelAgent.getStatus())) {
            agentRequest.setSubAgentId(channelAgent.getCAgentId()); //修改必填
        }
        agentRequest.setModifyUser("ls");
        agentRequest.setContactInfo(JSONObject.parseObject(channelAgent.getContactInfo(), ChannelContactInfo.class));
        agentRequest.setBaseInfo(JSONObject.parseObject(channelAgent.getBaseInfo(), ChannelBaseInfo.class));
        agentRequest.setSettleInfo(JSONObject.parseObject(channelAgent.getSettleInfo(), ChannelSettleInfo.class));
        agentRequest.setPicturesInfo(JSONObject.parseObject(channelAgent.getPicturesInfo(), ChannelPicturesInfo.class));
        agentRequest.setBusinessInfo(JSONObject.parseObject(channelAgent.getBusinessInfo(), ChannelBusinessInfo.class));
        strategy.updateAgent(channelAgent, agentRequest);
        return toAjax(channelAgentService.updateChannelAgent(channelAgent));
    }

    /**
     * 删除渠道代理商
     */
    @RequiresPermissions("channel:agent:remove")
    @Log(title = "渠道代理商", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] strArray = Convert.toStrArray(ids);
        for (String id : strArray) {
            ChannelAgent channelAgent = channelAgentService.selectChannelAgentById(id);
            agentPicturesInfoService.deleteAgentPicturesInfoByAgentId(channelAgent.getAgentId());
        }

        return toAjax(channelAgentService.deleteChannelAgentByIds(ids));
    }

    @PostMapping("/query")
    @ResponseBody
    public AjaxResult query(String ids) {
        String[] strArray = Convert.toStrArray(ids);
        for (String id : strArray) {
            ChannelAgent channelAgent = channelAgentService.selectChannelAgentById(id);
            TermDto termDto = new TermDto();
            termDto.setAgentId(CustomConfig.getSubAgentId());
            termDto.setSource(CustomConfig.getSource());
            termDto.setSubAgentId(channelAgent.getCAgentId());
            Map<String, Object> baseResult = LeShuaUtil.commonRemote(termDto, CustomConfig.getBaseUrl() + "/agentInfo/checkStatus", CustomConfig.getSignKey());
            channelAgent.setRemark(JSON.toJSONString(baseResult));
            channelAgentService.updateChannelAgent(channelAgent);
        }
        return AjaxResult.success("操作成功");
    }

    // 保存文件到本地（演示）
//    private String saveFile(String path) throws IOException {
//        String ext = path.split("\\.")[1];
//        String base64 = "";
//        if (UPLOAD_STRATEGY == 1) {
//            base64 = ImageUtil.encodeImageToBase64(BlueConfig.getAgentPath() + path.substring(path.indexOf("agent") + "agent".length()));
//        } else if (UPLOAD_STRATEGY == 2) {
//            base64 = convertImageToBase64(CustomConfig.getImgUrl() + path);
//        }
//        MerchantPicDto merchantPicDto = new MerchantPicDto();
//        merchantPicDto.setAgentId(CustomConfig.getSubAgentId());
//        merchantPicDto.setSource(CustomConfig.getSource());
//        merchantPicDto.setExt(ext);//扩展名，例如jpg/png;pdf
//        merchantPicDto.setPicData(base64);//base64编码的图片数据
//        merchantPicDto.setSign(LeShuaUtil.md5ParamByKey(merchantPicDto, ""));//签名
//        Map<String, Object> baseResult = LeShuaUtil.commonRemote(merchantPicDto, CustomConfig.getBaseUrl() + "/basicInfo/uploadMerchantPic", CustomConfig.getSignKey());
//        Map<String, String> respData = (Map<String, String>) baseResult.get("respData");
//        return respData.get("pictureTmpUrl");
//    }

    public static String convertImageToBase64(String imagePath) throws IOException {
        // 通过 Hutool 下载图片字节流
        byte[] imageBytes = HttpUtil.downloadBytes(imagePath);
        // Base64 编码
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public String uploadImg(MultipartFile imgFile) throws IOException {
        String clientName = imgFile.getOriginalFilename();
        if (StringUtils.isEmpty(clientName)) {
            return null;
        }
        String fileName = null;
        fileName = clientName.substring(clientName.indexOf("."), clientName.length());
        //临时文件
        File dfile = File.createTempFile("prefix", "_" + clientName);
        imgFile.transferTo(dfile);
        //上传至Fast的图片数据
        Map<String, String> metaList = new HashMap<String, String>();
        metaList.put("fileName", fileName);
        metaList.put("fileType", imgFile.getName());
        metaList.put("author", ShiroUtils.getSysUser().getLoginName());
        metaList.put("date", Utils.formateDate(2));//年月日 时分秒
        String fid = FastDFSClient.uploadFile(dfile, dfile.getName(), metaList);
        if (StringUtils.isEmpty(fid)) {
            throw new BusinessException("图片上传失败,请重新上传");
        }
        return fid;
    }

    /**
     * 根据上传策略上传文件
     */
    private String uploadFileByStrategy(MultipartFile file) throws IOException {
        if (CustomConfig.getUploadStrategy().equalsIgnoreCase("1")) {
            return FileUploadUtils.upload(BlueConfig.getAgentPath(), file);
        } else if (CustomConfig.getUploadStrategy().equalsIgnoreCase("2")) {
            return uploadImg(file);
        } else {
            throw new BusinessException("未知的上传策略");
        }
    }

}
